﻿using Airborne.ScrumPoker.Model.TeamFoundation;
using Airborne.ScrumPoker.Module.Developer.Views;
using Airborne.ScrumPoker.Module.Events;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Composite.Wpf.Events;
using Microsoft.Practices.Unity;

namespace Airborne.ScrumPoker.Module.Developer.Controllers
{
    public class WorkItemController : IWorkItemController
    {
          #region Constructor
        public WorkItemController (IRegionManager regionManager, IEventAggregator eventAggregator, IUnityContainer container)
        {
            RegionManager = regionManager;
            EventAggregator = eventAggregator;
            Container = container;
        }
        #endregion

        #region Properties
        private IRegionManager RegionManager { get; set; }
        private IEventAggregator EventAggregator { get; set; }
        private IUnityContainer Container { get; set; }
        private IWorkItemDetailView WorkItemDetailView { get; set; } 
        #endregion

        
        public void Run()
        {
            SubscribeToEvents();
            WorkItemDetailView = Container.Resolve<IWorkItemDetailView>();
            RegionManager.Regions[RegionNames.WorkItemRegion].AddAndActivate(WorkItemDetailView);
        }

        private void SubscribeToEvents()
        {
             EventAggregator.GetEvent<GenericEvent<ITeamWorkItem>>().Subscribe(WorkItemSelected, ThreadOption.UIThread, true, p=>p.Topic == EventTopics.WorkItemSelected);
        }

        private void WorkItemSelected(EventParameters<ITeamWorkItem> parameters)
        {
            WorkItemDetailView.WorkItem = parameters.Value;
        }
    }
}
